package com.travelSpring.controller;

import cn.hutool.core.io.FileUtil;
import com.travelSpring.common.Result;
import com.travelSpring.exception.UserException;
import com.travelSpring.service.ImageFileService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 功能：
 * 作者：卷心菜
 * 日期：2025/3/30 10:01
 */
@RestController
@RequestMapping("/files")

public class ImageFileController {

    @Autowired
    ImageFileService imageFileService;


    private static final String STORE_DIR=System.getProperty("user.dir");
    private static final String DOMAIN="http://localhost:8080/files/download";
//    //上传
//    @PostMapping("/upload")
//    public Result upload(@RequestParam("image") MultipartFile file) throws Exception {
//        //取文件名
//        String fileName = UUID.randomUUID().toString().substring(0, 10) + file.getOriginalFilename();
//        FileUtils.copyInputStreamToFile(file.getInputStream(),new File(STORE_DIR+fileName));
//        //图片访问url
//        String url = DOMAIN + fileName;
//        return Result.success(url);
//    }
//    //下载
//    @GetMapping("/download")
//    public void download(@PathVariable("fileName")String fileName,
//                         HttpServletRequest request,
//                         HttpServletResponse response) throws Exception {
//        String filePath = STORE_DIR + fileName;
//        System.out.println("完整路径"+filePath);
//        try{
//            //下载文件
//            //设置响应头
//            response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);
//            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+fileName);
//
//            //读取文件并写入输入框
//            Files.copy(Paths.get(filePath),response.getOutputStream());
//            response.getOutputStream().flush();
//        }catch(Exception e){
//            response.setStatus(404);
//        }
//    }
        //文件下载接口
        //下载路径http://localhost:8080/files/download/fileName
        @GetMapping("/download/{fileName}")
        public void download(@PathVariable String fileName, HttpServletResponse response) throws Exception {
            //找到文件位置
            String filePath = System.getProperty("user.dir") + "/files/";//获取文件夹路径，System.getProperty("user.dir")获取项目根路径
            String realPath = filePath + fileName;//获取文件路径 jpg路径
            boolean exist = FileUtil.exist(realPath);
            if(!exist) {
                throw new UserException("文件不存在");
            }
            //读取文件字节流
            byte[] bytes = FileUtil.readBytes(realPath);
            //输出流对象，把文件写出到客户端浏览器
            ServletOutputStream os = response.getOutputStream();
            os.write(bytes);
            os.flush();
            os.close();
        }
        //文件上传 MultipartFile(文件上传必要参数类型)
        //上传路径：http://localhost:8080/files/upload
        @PostMapping("/upload")
        public Result upload(@RequestParam("file") MultipartFile file) throws Exception {
            String filePath = System.getProperty("user.dir") + "/files/";
            if(!FileUtil.isDirectory(filePath)) {//判断是否有文件夹，如果没有就创建一个
                FileUtil.mkdir(filePath);
            }
            byte[] bytes = file.getBytes();
            String fileName =System.currentTimeMillis()+"_"+file.getOriginalFilename();//防止重复加入随机数
            //写入文件
            FileUtil.writeBytes(bytes, filePath+fileName);
            String url="http://localhost:8080/files/download/"+fileName;
            return Result.success(url);
        }

}
